 <?php
class Jquerypluginstype extends Model_Abstract
{
	public $tableName = 'jqueryplugins_type';
	
	
	protected $_validation = array(
		'name' => array(
			array('max_length', '模板名称长度不能超过100', 100),
			array('not_empty', '请填写模板名称')
		),
		'name_en' => array(
			array('max_length', '模板名称(en)长度不能超过100', 100),
			array('not_empty', '请填写模板名称')
		),
		'is_default' => array(
			array('in_array', 'is_default只能设为0或1', array(0, 1))
		)
	);
	
	public function init()
	{
		$this->initAttributes();
	}
	
	public static function model($classname = __CLASS__)
	{
		return parent::model($classname);
	}
	
	public function attributeLabels()
	{
		return array(
			'name' => '类型名称(Zh)',
			'name_en' => '类型名称(En)',
		);
	}

	protected function validate()
	{
		$ret = true;
		
		$ret2 = parent::validate();
		
		return ($ret && $ret2);
	}
	
	public function initAttributes()
	{
		$this->attributes = array(
			'name' => '',
			'name_en' => '',
			'is_default' => 0
		);
	}
	
	/**
	 * @see Model_Abstract::_delete()
	 * 删除类别的同时，将删除的类别影响到的htmltemplates设为默认值
	 */
	protected function _delete($attributes = array(), $conditions = array(), $params = array())
	{
		$willDeleteLine = $this->find('id', $attributes, $conditions, $params, array('stripName' => true));
		if(!empty($willDeleteLine)){
			parent::_delete($attributes, $conditions, $params);
			
			$defaultLine = $this->find('id', array('is_default' => 1), null, null, array('onlyOne' => true));
			if(!empty($defaultLine)){
				$defaultId = $defaultLine['id'];
			}else{
				$defaultId = 0;
			}
			
			$jqueryPluginsModel = new Jqueryplugins();
			$affectLines = $jqueryPluginsModel->find('*', array('type_id' => $willDeleteLine));
			if(!empty($affectLines)){
				foreach($affectLines as $k => $line){
					$jqueryPluginsModel->attributes = $line;
					$jqueryPluginsModel->attributes['type_id'] = $defaultId;
					$jqueryPluginsModel->save();
				}
			}
			
			return true;
		}
		
	}
	
	/**
	 * @param int $id
	 * 根据id设置is_default值为1，同时将htmltemplates中type_area_id为空或者0的记录，设其type_area_id为id
	 */
	public function setDefaultById($id)
	{
		$this->update(array('is_default' => 0));
		$this->attributes = array(
			$this->primaryKey => $id,
			'is_default' => 1
		);
		$this->attributes['is_default'] = 1;
		if($this->save()){
			$jqueryPluginsModel = new Jqueryplugins();
			$noTypeJqueryplugins = $jqueryPluginsModel->find('id', array('type_id' => array(0, '')));
			if(!empty($noTypeJqueryplugins)){
				foreach($noTypeJqueryplugins as $k => $temp){
					$jqueryPluginsModel->attributes = array(
						'id' => $temp['id'],
						'type_id' => $id
					);
					$jqueryPluginsModel->save();
				}
			}
			return true;
		}
		
	}
	
	
	

}